import { _decorator, Animation, AnimationState, AudioClip, AudioSource, Collider2D, Component, Contact2DType, find, IPhysics2DContact, Node, v2 } from 'cc';
import { Monster } from './Monster';
const { ccclass, property } = _decorator;

@ccclass('Bomb')
export class Bomb extends Monster {

    /**
     * 爆炸
     */
    @property({type:AudioClip})
    private bombclip:AudioClip = null
    private player:Node = null

    //bomb_idle,bomb_explosion
    anim ='bomb_idle'
    ani:Animation = null
    bombileAS:AudioSource = null

    start() {
        this.ani = this.node.getComponent(Animation)
        this.player = find('Canvas/MainLogic/Player')
        this.node.getComponent(Collider2D).on(Contact2DType.BEGIN_CONTACT,this.onBeginContact,this)
        this.ani.on(Animation.EventType.FINISHED,this.onAnimationEvent,this)
        this.setani('bomb_idle')
        this.bombileAS = this.node.getComponent(AudioSource)
    }

    onAnimationEvent(type: Animation.EventType, state: AnimationState) {
        if(state.name == 'bomb_explosion'){
            this.recovery()
        }
        
    }

    setani(anim){
        if(this.anim == anim) return
        this.anim = anim
        this.ani.play(anim)
    }
    
    onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact): void {
        if(otherCollider.group == 2){
            this.bombileAS.playOneShot(this.bombclip)
            this.setani('bomb_explosion')
        }
    }

    /**
     * 怪物节点初始化
     * @param monsterpoolnum 节点池编号
     */
    initialize(monsterpoolnum: number): void {
        this.player = find('Canvas/MainLogic/Player')
        this.setBombPosition()
        this.setani('bomb_idle')
        this.monsterpoolnum = monsterpoolnum
    }
    setBombPosition(){
        if(this.player.position.y>100){
            this.node.setPosition(this.node.position.x,this.getRandomInt(200,0),0)
        }else if(this.player.position.y<-100){
            this.node.setPosition(this.node.position.x,this.getRandomInt(-200,0),0)
        }else{
            this.node.setPosition(this.node.position.x,this.getRandomInt(-100,100),0)
        }
    }

    getRandomInt(min: number, max: number): number {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    update(deltaTime: number) {
        if(!this.player){
            this.player = find('Canvas/MainLogic/Player')
        }
        if(this.node.position.x -  this.player.position.x < -2000){
            this.recovery()
        }
    }
}


